<html>
<meta name="google-signin-client_id" content="XXX.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<a href="#" onclick="signOut();">Sign out</a>
<script>
  function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
    });
  }
</script>
<script>
// google's jwk is here: https://www.googleapis.com/oauth2/v3/certs
function randomString(length) {
    var bytes = new Uint8Array(length);
    var random = window.crypto.getRandomValues(bytes);
    var result = [];
    var charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._~'
    random.forEach(function (c) {
        result.push(charset[c % charset.length]);
    });
    return result.join('');
}

function getUrlParam(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&#]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function onSignIn(googleUser) {
  var id_token = googleUser.getAuthResponse().id_token;
  console.info(id_token)
  // trade for camic token
  var cookie_name = "token" // "token" is expected by elevate router
  var base_deployment_url = window.location.toString().split("/").slice(0,-1).join("/")
  var redirect_uri = base_deployment_url + "/login.html"
  var default_redirect = base_deployment_url + "/apps/table.html"
  var state
  if (getUrlParam("state"))
  {
    state = decodeURIComponent(getUrlParam("state"))
  }
  if (!state){
    state = default_redirect
  }

  if (id_token){
    document.cookie = cookie_name + "=" + id_token;
    fetch("./auth/Token/check",
    {headers: {
        'Authorization': "Bearer " + id_token
     }}
    ).then(x=>x.json()).then(x=>{
      console.log("{id provider", id_token)
      console.log("{auth service}", x)
      if (x.hasOwnProperty('token')){
        document.cookie = cookie_name + "=" + x.token;
        window.location = state
      } else {
        window.alert("User not added")
        window.location = "./apps/signup/signup.html"
      }

    })
  }
}


</script>
<html>
